package com.engine.wei.base.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 作者:赵若位
 * 时间:2021/8/25 16:43
 * 功能:基础的RecyclerView.Adapter
 */
public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {

    private Context mContext;
    private List<T> mData;

    private @LayoutRes
    int mLayoutRes;

    public BaseAdapter(@LayoutRes int layout) {
        this.mLayoutRes = layout;
        mData = new ArrayList<>();
    }

    private void checkoutData() {
        if (null == mData) {
            mData = new ArrayList<>();
        }
    }

    public void setNewData(@NonNull T... data) {
        checkoutData();
        mData.clear();
        mData.addAll(new ArrayList<>(Arrays.asList(data)));
        notifyDataSetChanged();
    }

    public void setNewData(@NonNull List<T> list) {
        checkoutData();
        mData.clear();
        if (null != list && !list.isEmpty()) {
            mData.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void setData(@NonNull T data) {
        checkoutData();
        if (null != data) {
            mData.add(data);
            notifyItemInserted(mData.size() - 1);
        }
    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View layout = LayoutInflater.from(parent.getContext().getApplicationContext()).inflate(mLayoutRes, parent, false);
        return BaseViewHolder.createViewHolder(layout);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        convert(holder, position, mData.get(position));
    }

    @Override
    public int getItemCount() {
        return null == mData || mData.isEmpty() ? 0 : mData.size();
    }


    abstract void convert(@NonNull BaseViewHolder holder, int position, @NonNull T data);
}
